package core;

import java.awt.Toolkit;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;

/**
 * 通过类注解创建Scene对象
 * @author self
 *
 */
public class SceneFactory {

	public static Parent autoScalePanel(Parent parent){
		int screenWidth = Toolkit.getDefaultToolkit().getScreenResolution();
		parent.setStyle("-fx-font-size:"+String.format("%1$.2f", Math.floor(240/screenWidth)*12)+"pt;");
		return parent;
	}

	/**
	 * 创建Scene的顶级组件
	 * @return　顶级组件对象
	 * @throws Exception 使用反射查询类注解，可能发生异常
	 */
	private static Parent createViewRoot() throws Exception {

		/**
		 * 遍历调用堆栈，查找调用类的FxmlView注解
		 */
		StackTraceElement[] callStackList = Thread.currentThread().getStackTrace();
		Class<?> clientViewClass=null;
		for(int i=1;i<callStackList.length;i++) {
			Class<?> clazz = Class.forName(callStackList[i].getClassName());
			if(clazz.getAnnotation(FxmlView.class)!=null) {
				clientViewClass=clazz;
				break;
			}
		}

		if(clientViewClass==null)
			throw new IllegalAccessException("Must be has FxmlView annotation!");

		//获取fxml文件名称
		String fxml = clientViewClass.getAnnotation(FxmlView.class).value();
		//加载fxml（fxml文件与使用类应处于同一包下）
		return autoScalePanel(FXMLLoader.load(clientViewClass.getResource(fxml)));
	}

	public static Scene create() throws Exception {
		return new Scene(createViewRoot());
	}

	public static Scene create(int width,int height) throws Exception {
		return new Scene(createViewRoot());
	}
}
